package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpCollectProductFreightTask;
import com.erp.gather.domain.bo.ErpCollectProductFreightTaskBo;
import com.erp.gather.domain.vo.ErpCollectProductFreightTaskVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpCollectProductFreightTaskService;
import com.erp.gather.service.IErpCollectProductSkuPriceService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerCollectProductExpand;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品运费试算任务Service业务层处理
 *
 * @author erp
 * @date 2023-04-20
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductFreightTaskServiceImpl implements IErpCollectProductFreightTaskService {

	private final ErpCollectProductFreightTaskMapper baseMapper;
	private final ErpCollectProductMapper collectProductMapper;
	private final ErpCollectProductSkuMapper collectProductSkuMapper;
	private final ErpCollectProductExpandMapper collectProductExpandMapper;
	private final ErpProductAreaMapper erpProductAreaMapper;
	private final ErpProductArea64Mapper erpProductArea64Mapper;
	private final IErpCollectProductSkuPriceService iErpCollectProductSkuPriceService;
	private final ErpSellerCollectProductMapper erpSellerCollectProductMapper;
	private final ErpSellerCollectProductSkuMapper erpSellerCollectProductSkuMapper;
	private final ErpSellerCollectProductExpandMapper erpSellerCollectProductExpandMapper;
	private final ErpCollectProductOptimizeMapper collectProductOptimizeMapper;
	private final ErpCollectProductSplitLogMapper erpCollectProductSplitLogMapper;

	/**
	 * 查询采集商品运费试算任务
	 */
	@Override
	public ErpCollectProductFreightTaskVo queryById(Long id) {
		return baseMapper.selectVoById(id);
	}

	/**
	 * 查询采集商品运费试算任务列表
	 */
	@Override
	public TableDataInfo<ErpCollectProductFreightTaskVo> queryPageList(ErpCollectProductFreightTaskBo bo,
																	   PageQuery pageQuery) {
		LambdaQueryWrapper<ErpCollectProductFreightTask> lqw = buildQueryWrapper(bo);
		Page<ErpCollectProductFreightTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
		return TableDataInfo.build(result);
	}

	/**
	 * 查询采集商品运费试算任务列表
	 */
	@Override
	public List<ErpCollectProductFreightTaskVo> queryList(ErpCollectProductFreightTaskBo bo) {
		LambdaQueryWrapper<ErpCollectProductFreightTask> lqw = buildQueryWrapper(bo);
		return baseMapper.selectVoList(lqw);
	}

	private LambdaQueryWrapper<ErpCollectProductFreightTask> buildQueryWrapper(ErpCollectProductFreightTaskBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<ErpCollectProductFreightTask> lqw = Wrappers.lambdaQuery();
		lqw.eq(bo.getCollectProductId() != null, ErpCollectProductFreightTask::getCollectProductId,
				bo.getCollectProductId());
		lqw.eq(bo.getStatus() != null, ErpCollectProductFreightTask::getStatus, bo.getStatus());
		lqw.eq(bo.getAddTime() != null, ErpCollectProductFreightTask::getAddTime, bo.getAddTime());
		return lqw;
	}

	/**
	 * 新增采集商品运费试算任务
	 */
	@Override
	public Boolean insertByBo(ErpCollectProductFreightTaskBo bo) {
		ErpCollectProductFreightTask add = BeanUtil.toBean(bo, ErpCollectProductFreightTask.class);
		validEntityBeforeSave(add);
		boolean flag = baseMapper.insert(add) > 0;
		if (flag) {
			bo.setId(add.getId());
		}
		return flag;
	}

	/**
	 * 修改采集商品运费试算任务
	 */
	@Override
	public Boolean updateByBo(ErpCollectProductFreightTaskBo bo) {
		ErpCollectProductFreightTask update = BeanUtil.toBean(bo, ErpCollectProductFreightTask.class);
		validEntityBeforeSave(update);
		return baseMapper.updateById(update) > 0;
	}

	/**
	 * 保存前的数据校验
	 */
	private void validEntityBeforeSave(ErpCollectProductFreightTask entity) {
		// TODO 做一些数据校验,如唯一约束
	}

	/**
	 * 批量删除采集商品运费试算任务
	 */
	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			// TODO 做一些业务上的校验,判断是否需要校验
		}
		return baseMapper.deleteBatchIds(ids) > 0;
	}

	/**
	 * 获取未计算的运费计算任务，进行计算-----4px
	 */
//	@Override
//	@Async
//	public void computeFreight() {
//
//		Map<String, Double> cacheMap = new HashMap<String, Double>();
//
//		// 获取国家
//		List<ErpProductArea> selectList = erpProductAreaMapper.selectList();
//
//		LambdaQueryWrapper<ErpCollectProductFreightTask> lqw = new LambdaQueryWrapper<ErpCollectProductFreightTask>();
//		lqw.eq(ErpCollectProductFreightTask::getStatus, 0);
//		lqw.orderByAsc(ErpCollectProductFreightTask::getAddTime);
//		lqw.last(" limit 1");
//		ErpCollectProductFreightTask task = baseMapper.selectOne(lqw);
//		if (task == null)
//			return;
//
//		// 判断是哪种产品
//		Integer type = task.getType();
//		if (type.equals(1)) {
//
//			// 获取扩展信息
//			ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
//					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
//							.eq(ErpCollectProductExpand::getCollectProductId, task.getCollectProductId()));
//			if (collectProductExpand == null)
//				return;
//
//			// 修改为计算中
//			collectProductExpand.setIsFreight(2);
//			collectProductExpandMapper.updateById(collectProductExpand);
//			task.setStatus(1); // 计算中
//			baseMapper.updateById(task);
//
//			List<Object> list = new ArrayList<Object>();
//			// 获取采集商品sku
//			List<ErpCollectProductSku> skuList = collectProductSkuMapper
//					.selectList(new LambdaQueryWrapper<ErpCollectProductSku>()
//							.eq(ErpCollectProductSku::getCollectProductId, task.getCollectProductId()));
//
//			for (ErpProductArea erpProductArea : selectList) {
//
//				String areaNo = erpProductArea.getAreaNo();
//
//				Map<String, Object> map = new HashMap<String, Object>();
//				if (areaNo.equals("GB"))
//					map.put("shiptoCountry", "UK");
//				else
//					map.put("shiptoCountry", areaNo);
//
//				Map<String, Double> skuMap = new HashMap<String, Double>();
//				for (ErpCollectProductSku erpCollectProductSku : skuList) {
//					String skuWeight = erpCollectProductSku.getSkuWeight().toString();
//					String skuWidth = erpCollectProductSku.getSkuWidth().toString();
//					String skuHeight = erpCollectProductSku.getSkuHeight().toString();
//					String skuLength = erpCollectProductSku.getSkuLength().toString();
//
//					// 获取sku标识
//					String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
//
//					String key = skuWeight + "-" + skuWidth + "-" + skuHeight + "-" + skuLength + "-" + "-" + skuLength
//							+ "-" + areaNo;
//
//					// 首先获取缓存map有值吗
//					Double priceCalculator = cacheMap.get(key);
//					if (priceCalculator != null) {
//						skuMap.put(skuPropertyIds, priceCalculator);
//					} else {
//						String areaNoNew = areaNo;
//						if (areaNo.equals("MA"))
//							areaNoNew = "US";
//
//						// 首先获取数据库中是否有记录
//						AeProductFreight aeProductFreight = aeProductFreightMapper.selectOne(
//								new LambdaQueryWrapper<AeProductFreight>().eq(AeProductFreight::getLength, skuLength)
//										.eq(AeProductFreight::getWeight, skuWeight)
//										.eq(AeProductFreight::getHeight, skuHeight)
//										.eq(AeProductFreight::getWidth, skuWidth)
//										.eq(AeProductFreight::getCountry, areaNoNew).last(" limit 1 "));
//						if (aeProductFreight != null) {
//							priceCalculator = aeProductFreight.getFreight().doubleValue();
//							if (areaNo.equals("MA")) {
//								priceCalculator = new BigDecimal(priceCalculator * 1.6)
//										.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//							}
//						} else {
//							priceCalculator = Px4Utils.priceCalculator(skuWeight, skuWidth, skuLength, skuHeight,
//									areaNoNew);
//							if (!priceCalculator.equals(0d)) {
//
//								// 增加10%的费用
//								priceCalculator = new BigDecimal(priceCalculator * 1.6)
//										.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//								if (areaNo.equals("MA")) {
//									priceCalculator = new BigDecimal(priceCalculator * 1.6)
//											.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//								}
//
//								// 保存到数据库中
//								if (areaNo.equals(areaNoNew)) {
//									aeProductFreight = new AeProductFreight();
//									aeProductFreight.setCountry(areaNo);
//									aeProductFreight.setFreight(new BigDecimal(priceCalculator));
//									aeProductFreight.setHeight(skuHeight);
//									aeProductFreight.setLength(skuLength);
//									aeProductFreight.setWeight(skuWeight);
//									aeProductFreight.setWidth(skuWidth);
//									aeProductFreightMapper.insert(aeProductFreight);
//								}
//							}
//						}
//						skuMap.put(skuPropertyIds, priceCalculator);
//						cacheMap.put(key, priceCalculator);
//					}
//				}
//				map.put("absoluteQuoteMap", skuMap);
//				list.add(map);
//			}
//			collectProductExpand.setFreightMap(JsonUtils.toJsonString(list));
//			collectProductExpand.setIsFreight(3); // 计算完成
//			collectProductExpandMapper.updateById(collectProductExpand);
//
//			task.setStatus(2); // 计算完成
//			baseMapper.updateById(task);
//
//			// 保存产品成本记录
//			iErpCollectProductSkuPriceService.saveSkuPrice(task.getCollectProductId());
//		} else if (type.equals(2)) { // 个人采集
//			// 获取扩展信息
//			ErpSellerCollectProductExpand collectProductExpand = erpSellerCollectProductExpandMapper
//					.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
//							.eq(ErpSellerCollectProductExpand::getCollectProductId, task.getCollectProductId()));
//			if (collectProductExpand == null)
//				return;
//
//			// 修改为计算中
//			collectProductExpand.setIsFreight(2);
//			erpSellerCollectProductExpandMapper.updateById(collectProductExpand);
//			task.setStatus(1); // 计算中
//			baseMapper.updateById(task);
//
//			List<Object> list = new ArrayList<Object>();
//			// 获取采集商品sku
//			List<ErpSellerCollectProductSku> skuList = erpSellerCollectProductSkuMapper
//					.selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
//							.eq(ErpSellerCollectProductSku::getCollectProductId, task.getCollectProductId()));
//
//			for (ErpProductArea erpProductArea : selectList) {
//
//				String areaNo = erpProductArea.getAreaNo();
//
//				Map<String, Object> map = new HashMap<String, Object>();
//				if (areaNo.equals("GB"))
//					map.put("shiptoCountry", "UK");
//				else
//					map.put("shiptoCountry", areaNo);
//
//				Map<String, Double> skuMap = new HashMap<String, Double>();
//				for (ErpSellerCollectProductSku erpCollectProductSku : skuList) {
//					String skuWeight = erpCollectProductSku.getSkuWeight().toString();
//					String skuWidth = erpCollectProductSku.getSkuWidth().toString();
//					String skuHeight = erpCollectProductSku.getSkuHeight().toString();
//					String skuLength = erpCollectProductSku.getSkuLength().toString();
//
//					// 获取sku标识
//					String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
//
//					String key = skuWeight + "-" + skuWidth + "-" + skuHeight + "-" + skuLength + "-" + "-" + skuLength
//							+ "-" + areaNo;
//
//					// 首先获取缓存map有值吗
//					Double priceCalculator = cacheMap.get(key);
//					if (priceCalculator != null) {
//						skuMap.put(skuPropertyIds, priceCalculator);
//					} else {
//						String areaNoNew = areaNo;
//						if (areaNo.equals("MA"))
//							areaNoNew = "US";
//
//						// 首先获取数据库中是否有记录
//						AeProductFreight aeProductFreight = aeProductFreightMapper.selectOne(
//								new LambdaQueryWrapper<AeProductFreight>().eq(AeProductFreight::getLength, skuLength)
//										.eq(AeProductFreight::getWeight, skuWeight)
//										.eq(AeProductFreight::getHeight, skuHeight)
//										.eq(AeProductFreight::getWidth, skuWidth)
//										.eq(AeProductFreight::getCountry, areaNoNew).last(" limit 1 "));
//						if (aeProductFreight != null) {
//							priceCalculator = aeProductFreight.getFreight().doubleValue();
//							if (areaNo.equals("MA")) {
//								priceCalculator = new BigDecimal(priceCalculator * 1.6)
//										.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//							}
//						} else {
//							priceCalculator = Px4Utils.priceCalculator(skuWeight, skuWidth, skuLength, skuHeight,
//									areaNoNew);
//							if (!priceCalculator.equals(0d)) {
//
//								// 增加10%的费用
//								priceCalculator = new BigDecimal(priceCalculator * 1.6)
//										.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//								if (areaNo.equals("MA")) {
//									priceCalculator = new BigDecimal(priceCalculator * 1.6)
//											.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//								}
//
//								// 保存到数据库中
//								if (areaNo.equals(areaNoNew)) {
//									aeProductFreight = new AeProductFreight();
//									aeProductFreight.setCountry(areaNo);
//									aeProductFreight.setFreight(new BigDecimal(priceCalculator));
//									aeProductFreight.setHeight(skuHeight);
//									aeProductFreight.setLength(skuLength);
//									aeProductFreight.setWeight(skuWeight);
//									aeProductFreight.setWidth(skuWidth);
//									aeProductFreightMapper.insert(aeProductFreight);
//								}
//							}
//						}
//						skuMap.put(skuPropertyIds, priceCalculator);
//						cacheMap.put(key, priceCalculator);
//					}
//				}
//				map.put("absoluteQuoteMap", skuMap);
//				list.add(map);
//			}
//			collectProductExpand.setFreightMap(JsonUtils.toJsonString(list));
//			collectProductExpand.setIsFreight(3); // 计算完成
//			erpSellerCollectProductExpandMapper.updateById(collectProductExpand);
//
//			task.setStatus(2); // 计算完成
//			baseMapper.updateById(task);
//
//			// 保存产品成本记录
////			iErpCollectProductSkuPriceService.saveSkuPrice(task.getCollectProductId());
//		}
//	}
	
	@Override
	public void refresh(Long collectProductId, Integer type) {
		
		type = 1;

		if (type.equals(1)) {
			// 修改状态
			ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
							.eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
			collectProductExpand.setIsFreight(1); // 等待计算
			collectProductExpandMapper.updateById(collectProductExpand);
		} else {
			ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
							.eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
			expand.setIsFreight(1); // 等待计算
			erpSellerCollectProductExpandMapper.updateById(expand);
		}
		// 获取是否有记录
		ErpCollectProductFreightTask collectProductFreightTask = baseMapper
				.selectOne(new LambdaQueryWrapper<ErpCollectProductFreightTask>()
						.eq(ErpCollectProductFreightTask::getCollectProductId, collectProductId)
						.eq(ErpCollectProductFreightTask::getType, type).last("limit 1"));
		if (collectProductFreightTask == null) {
			// 保存商品运费试算
			collectProductFreightTask = new ErpCollectProductFreightTask();
			collectProductFreightTask.setType(type);
			collectProductFreightTask.setCollectProductId(collectProductId);
			collectProductFreightTask.setAddTime(new Date());
			baseMapper.insert(collectProductFreightTask);
		} else {
			collectProductFreightTask.setStatus(0);
			baseMapper.updateById(collectProductFreightTask);
		}
	}

	/**
	 * type 1公共代表采集商品，2代表个人采集
	 */
	@Override
	@Async
	public void save(Long collectProductId, Integer type) {
		type = 1;

		// 获取是否有记录
		ErpCollectProductFreightTask collectProductFreightTask = baseMapper
				.selectOne(new LambdaQueryWrapper<ErpCollectProductFreightTask>()
						.eq(ErpCollectProductFreightTask::getCollectProductId, collectProductId)
						.eq(ErpCollectProductFreightTask::getType, type).last("limit 1"));
		if (collectProductFreightTask == null) {
			// 保存商品运费试算
			collectProductFreightTask = new ErpCollectProductFreightTask();
			collectProductFreightTask.setType(type);
			collectProductFreightTask.setCollectProductId(collectProductId);
			collectProductFreightTask.setAddTime(new Date());
			baseMapper.insert(collectProductFreightTask);

		} else {
			collectProductFreightTask.setStatus(0);
			baseMapper.updateById(collectProductFreightTask);
		}
		if (type.equals(1)) {
			// 修改状态
			ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
							.eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
			collectProductExpand.setIsFreight(1); // 等待计算
			collectProductExpandMapper.updateById(collectProductExpand);
		} else {
			ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
							.eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
			expand.setIsFreight(1); // 等待计算
			erpSellerCollectProductExpandMapper.updateById(expand);
		}

	}

}
